# -*- coding: utf-8 -*-
#   数据表转换成列表字段形式
# @Time    ： 2023/2/25  11:57
# @Auther  ： 徐良
# File     :  tableToList.py

from PySide6.QtCore import Qt
from share.dataFactory import DataFactory
from share.baseFunction import getInstanceType


class FcToDict(object):
    """
    父子表不在同一个table里，将父子表转换成父子list
    """

    def __init__(self, dic):
        super(FcToDict, self).__init__()
        self.__list = None
        self.__childList = None
        self.fSql = dic['fTableSql']
        self.cSql = dic['cTableSql']
        self.__getModel()
        self.__getTableFieldsList()

    # 获取model
    def __getModel(self):
        self.__fModel = DataFactory.getQueryModelForSql(self.fSql)
        idList = []
        for r in range(0, self.__fModel.rowCount()):
            idList.append(str(self.__fModel.record(r).value('fid')))
        ids = ','.join(idList)
        sql = self.cSql.format(ids=ids)
        self.__cModel = DataFactory.getQueryModelForSql(sql)

    # 获取model全部字段名
    def __getTableFieldsList(self):
        self.__fieldsList = []
        column = self.__fModel.columnCount()
        for i in range(0, column):
            self.__fieldsList.append(str(self.__fModel.headerData(i, Qt.Horizontal, Qt.DisplayRole)).lower())

        self.__cFieldsList = []
        column = self.__cModel.columnCount()
        for i in range(0, column):
            self.__cFieldsList.append(str(self.__cModel.headerData(i, Qt.Horizontal, Qt.DisplayRole)).lower())

    # 获取列表字典
    def getListDict(self):

        def appendPList(record):
            d = {}
            for f in self.__fieldsList:
                d[f] = record.value(f)
            self.__list.append(d)

        def appendChildList(record):
            lList = []
            xid = record.value('fid')
            for x in range(0, self.__cModel.rowCount()):
                if xid == self.__cModel.record(x).value('fentityid'):
                    c = {}
                    for f in self.__cFieldsList:
                        c[f] = self.__cModel.record(x).value(f)
                    lList.append(c)
            self.__childList.append(lList)

        ret = {}
        self.__list = []
        self.__childList = []

        for i in range(0, self.__fModel.rowCount()):
            appendPList(self.__fModel.record(i))
            appendChildList(self.__fModel.record(i))

        ret['list'] = self.__list
        ret['childList'] = self.__childList
        return ret


class TableToListForPC(object):
    """
    父子表在同一个table里，转换成父子list
    """

    def __init__(self, sStr, sDbType=None):
        super(TableToListForPC, self).__init__()

        if sDbType is None:
            self.dbType = 'mysql'   # 默认是mysql
        else:
            self.dbType = sDbType

        self.__list = None
        self.__childList = None
        self.sql = sStr
        self.__getModel()
        self.__getTableFieldsList()


    # 获取model
    def __getModel(self):
        self.__model = DataFactory.getQueryModelForSql(self.sql, self.dbType)

    # 获取model全部字段名
    def __getTableFieldsList(self):
        self.__fieldsList = []
        column = self.__model.columnCount()
        for i in range(0, column):
            self.__fieldsList.append(str(self.__model.headerData(i, Qt.Horizontal, Qt.DisplayRole)).lower())

    def getListDict(self):
        """
        获取列表字典
        :return:
        """

        def appendPList(record):
            d = {}
            for f in self.__fieldsList:
                d[f] = record.value(f)
            self.__list.append(d)

        def appendChildList(record):
            lList = []
            xid = record.value('fid')
            for x in range(0, self.__model.rowCount()):
                if (xid == self.__model.record(x).value('fparentid') and
                        self.__model.record(x).value('flevel') == 2):
                    c = {}
                    for f in self.__fieldsList:
                        c[f] = self.__model.record(x).value(f)
                    lList.append(c)
            self.__childList.append(lList)

        ret = {}
        self.__list = []
        self.__childList = []

        for i in range(0, self.__model.rowCount()):
            if self.__model.record(i).value('flevel') == 1:
                appendPList(self.__model.record(i))
                appendChildList(self.__model.record(i))

        ret['list'] = self.__list
        ret['childList'] = self.__childList
        return ret


class TableToListDict(object):
    """
    将table记录格式转换成列表字典格式
    """

    def __init__(self, sStr):
        super(TableToListDict, self).__init__()
        self.__list = None
        self.sql = sStr
        self.__getModel()
        self.__getTableFieldsList()

    # 获取model
    def __getModel(self):
        self.__model = DataFactory.getQueryModelForSql(self.sql)

    # 获取model全部字段名
    def __getTableFieldsList(self):
        self.__fieldsList = []
        column = self.__model.columnCount()
        for i in range(0, column):
            self.__fieldsList.append(str(self.__model.headerData(i, Qt.Horizontal, Qt.DisplayRole)).lower())

    def getListDict(self):
        """
        获取列表字典
        :return:list
        """
        def appendList(record):
            d = {}
            for f in self.__fieldsList:
                val = record.value(f)
                if getInstanceType(val) == 'QDate':
                    v = val.toString("yyyy-MM-dd")
                elif getInstanceType(val) == 'QDateTime':
                    v = val.toString("yyyy-MM-dd hh:mm:ss")
                else:
                    v = val

                d[f] = v
            self.__list.append(d)

        ret = {}
        self.__list = []

        for i in range(0, self.__model.rowCount()):
            appendList(self.__model.record(i))


        return self.__list


class ModelToList(object):
    """
    父子表不在同一个table里，将父子表转换成父子list
    """

    def __init__(self, model, fieldList=None):
        super(ModelToList, self).__init__()
        self.__list = []
        self.__model = model
        if fieldList is not None:
            self.__fieldsList = fieldList
        else:
            self.__fieldsList = []
            self.__getTableFieldsList()

    # 获取model全部字段名
    def __getTableFieldsList(self):
        self.__fieldsList = []
        column = self.__model.columnCount()
        for i in range(0, column):
            self.__fieldsList.append(str(self.__model.headerData(i, Qt.Horizontal, Qt.DisplayRole)).lower())

    def __appendPList(self, record):
        d = {}
        for f in self.__fieldsList:
            d[f] = record.value(f)
        self.__list.append(d)

    def getListDict(self):
        """
        获取列表字典
        :return:
        """
        for i in range(0, self.__model.rowCount()):
            self.__appendPList(self.__model.record(i))

        return self.__list

    def getListDictBySel(self):
        """
        获取列表字典, 条件：FSel字段=1
        :return:
        """
        for i in range(0, self.__model.rowCount()):
            if self.__model.record(i).value('FSel') == 1:
                self.__appendPList(self.__model.record(i))

        return self.__list


class ListFromModel(object):
    """
    从model中获取值的list和获取字段名list
    """

    def __init__(self, model):
        self._model = model

    def getValueList(self):
        """
        获取value 的list  两维数据
        :return:
        """

        def getRecord(rowNo, fList):

            def getValue(val):
                if getInstanceType(val) == 'QDate':
                    v = val.toString("yyyy-MM-dd")
                elif getInstanceType(val) == 'QDateTime':
                    v = val.toString("yyyy-MM-dd hh:mm:ss")
                else:
                    v = val
                return v

            r = []
            for fn in fList:
                value = getValue(self._model.record(rowNo).value(fn))
                r.append(value)
            return r

        fieldList = self.getFieldList()
        rows = self._model.rowCount()
        valueList = []
        for i in range(0, rows):
            record = getRecord(i, fieldList)
            valueList.append(record)

        return valueList

    def getFieldList(self):
        """
        获取model字段名list
        :return:
        """
        fList = []
        column = self._model.columnCount()
        for i in range(0, column):
            fList.append(str(self._model.headerData(i, Qt.Horizontal, Qt.DisplayRole)).lower())

        return fList
